package com.youseu.taoliving.commodity.service.impl;

import com.youseu.taoliving.commodity.entity.*;
import com.youseu.taoliving.commodity.service.*;
import com.youseu.taoliving.commodity.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youseu.common.utils.PageUtils;
import com.youseu.common.utils.Query;

import com.youseu.taoliving.commodity.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        //查询条件
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(item -> {
                item.eq("id", key).or().like("spu_name", key);
            });
        }
        //状态
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status", status);
        }
        //品牌id 前端传0过来表示查询时不带该条件
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        //分类id
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private SpuImagesService spuImagesService;

    @Resource
    private AttrService attrService;

    @Resource
    private ProductAttrValueService productAttrValueService;

    @Resource
    private SkuInfoService skuInfoService;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO spuSaveVO) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        //将数据拷贝到spuInfoEntity
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        //保存基本信息
        this.saveBaseSpuInfo(spuInfoEntity);

        //保存介绍图片信息
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        //可能有多个介绍图片
        List<String> decript = spuSaveVO.getDecript();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        if (decript.size() == 0) {
            //没有介绍图片则设置一个默认图片
            spuInfoDescEntity.setDecript("default.jpg");
        } else {
            //将图片地址用逗号分割 再保存
            spuInfoDescEntity.setDecript(String.join(",", decript));
        }
        spuInfoDescService.saveSpuInfoDest(spuInfoDescEntity);

        //保存商品图集信息
        List<String> images = spuSaveVO.getImages();
        spuImagesService.saveSpuImg(spuInfoEntity.getId(), images);

        //保存spu属性信息
        //拿到属性 遍历添加
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setAttrId(item.getAttrId());
            //属性名前端没有传过来 需要调用attrService查表二次处理
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueEntities);

        //保存sku属性信息
        List<Skus> skus = spuSaveVO.getSkus();
        if (skus != null && skus.size() != 0) {
            //这里不适用流式计算 流失计算是懒加载
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                String defalutImg = "default.jpg";
                for (Images image : item.getImages()) {
                    //设置默认图片
                    if (image.getDefaultImg() == 1) {
                        defalutImg = image.getImgUrl();
                        skuInfoEntity.setSkuDefaultImg(defalutImg);
                        break;
                    }
                }
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setPrice(item.getPrice());
                skuInfoEntity.setSkuName(item.getSkuName());
                skuInfoEntity.setSkuTitle(item.getSkuTitle());
                skuInfoEntity.setSkuSubtitle(item.getSkuSubtitle());
                //保存sku信息
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //保存sku图片集信息
                List<SkuImagesEntity> imagesEntityList = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setImgSort(0);
                    return skuImagesEntity;
                }).filter(//过滤掉空图片
                        skuImagesEntity -> StringUtils.isNotBlank(skuImagesEntity.getImgUrl())
                ).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntityList);

                //保存sku销售属性
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> attrSalesList = attr.stream().map(attribute -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attribute, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuSaleAttrValueEntity.setAttrSort(0);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrSalesList);
            });


        }

    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void up(Long spuId) {
        baseMapper.updateSpuStatus(spuId, 1);
    }

    @Override
    public void down(Long spuId) {
        baseMapper.updateSpuStatus(spuId,2);
    }

}